package com.ant.storage.service.impl;

import com.ant.storage.mapper.ExcelDataEntityMapper;
import com.ant.storage.pojo.ExcelDataEntity;
import com.ant.storage.service.IExcelDataEntityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-29
 */
@Service
public class ExcelDataEntityServiceImpl extends ServiceImpl<ExcelDataEntityMapper, ExcelDataEntity> implements IExcelDataEntityService {
    @Override
    public List<ExcelDataEntity> listTree() {
        // 1. 查询所有符合条件的字典数据（也可分页，视需求而定）
        List<ExcelDataEntity> dicList = baseMapper.selectList(null); // 自定义方法：按类型查询
        // 2. 筛选顶级节点（parentId = 0 或 null）
        List<ExcelDataEntity> topNodes = dicList.stream()
                .filter(dic -> dic.getParentId() == null || dic.getParentId() == 0)
                .collect(Collectors.toList());
        // 3. 为每个顶级节点递归设置子节点
        for (ExcelDataEntity topNode : topNodes) {
            setChildren(topNode, dicList);
        }
        return topNodes;
    }


    /**
     * 递归为节点设置子节点
     * @param parentNode 父节点
     * @param allDics 所有字典数据（避免多次查询数据库）
     */
    private void setChildren(ExcelDataEntity parentNode, List<ExcelDataEntity> allDics) {
        // 筛选当前父节点的子节点（parentId = 父节点 id）
        List<ExcelDataEntity> children = allDics.stream()
                .filter(dic -> parentNode.getId().equals(dic.getParentId()))
                .collect(Collectors.toList());

        // 若有子节点，继续递归设置子节点的子节点
        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            for (ExcelDataEntity child : children) {
                setChildren(child, allDics); // 递归
            }
        }
    }
}
